<template>
  <page-lr class="page-industry-info-manage">
    <div :style="{height: domHeight + 'px',overflow: 'hidden'}" slot="content-right">
      <el-scrollbar style="height:100%">
        <el-form size="small" :model="searchForm" label-width="110px">
          <el-form-item label="污染源名称：">
            <el-input placeholder="输入污染源名称" v-model="searchForm.name" clearable class="btn-search">
              <el-button slot="append" icon="el-icon-search" size="small" type="primary" @click="getList()"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="区域：">
            <el-select v-model="searchForm.county" placeholder="请选择" style="width:100%;" :disabled="userInfo.is_region_user">
              <el-option v-for="(item,index) in initData.countys" :key="index" :label="item.name" :value="item.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="污染源类别：" class="form-class">
            <el-checkbox-group v-model="searchForm.class" @change="changeClass">
              <el-checkbox v-for="(item,index) in initData.classes" :key="index" :label="item.label" >
                {{item.label}}
            </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="工业行业：" class="height-auto" v-if="searchForm.class.indexOf('工业源') != -1">
            <el-checkbox :indeterminate="indeterminateIndustries" v-model="checkedAllIndustries" @change="changeCheckAllIndustries">全选</el-checkbox>
            <el-select
              v-model="searchForm.industries"
              multiple
              collapse-tags
              class="select-industries"
              style="margin-left: 0px;height:auto;width:100%;"
              placeholder="请选择"
              @change="changeIndustries">
              <el-option
                v-for="item in initData.industries"
                :key="item.id"
                :label="item.text"
                :value="item.text">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="SO₂排放≥：">
            <el-input v-model="searchForm.so2" placeholder="请输入" type="number" clearable>
              <span slot="suffix">吨/年</span>
            </el-input>
          </el-form-item>
          <el-form-item label="NOx排放≥：">
            <el-input v-model="searchForm.nox" placeholder="请输入" type="number" clearable>
              <span slot="suffix">吨/年</span>
            </el-input>
          </el-form-item>
          <el-form-item label="PM₁₀排放≥：">
            <el-input v-model="searchForm.pm10" placeholder="请输入" type="number" clearable>
              <span slot="suffix">吨/年</span>
            </el-input>
          </el-form-item>
          <el-form-item label="PM₂.₅排放≥：">
            <el-input v-model="searchForm.pm25" placeholder="请输入" type="number" clearable> 
              <span slot="suffix">吨/年</span>
            </el-input>
          </el-form-item>
          <el-form-item label="VOCs排放≥：">
            <el-input v-model="searchForm.vocs" placeholder="请输入" type="number" clearable>
              <span slot="suffix">吨/年</span>
            </el-input>
          </el-form-item>
          <el-form-item >
            <el-button icon="el-icon-refresh" size="small" @click="resetSearch">重置</el-button>
            <el-button type="primary" icon="el-icon-search" size="small" @click="getList()">查询</el-button>
          </el-form-item>
        </el-form>
      </el-scrollbar>
    </div>
    <template slot="content-left">
      <div class="btn-group align-right m-b-15">
        <!-- <el-button icon="el-icon-plus" size="small" type="primary" @click="handleOperate('editIndustry',{},'add')">新增</el-button> -->
        <el-button icon="el-icon-refresh" size="small" style="margin-right:8px;" @click="getList(page.current)">重置</el-button> 
        <el-dropdown>
          <el-button type="primary" size="small" icon="el-icon-plus">
            新增
          </el-button>
          <el-dropdown-menu slot="dropdown" class="add-menu">
            <el-dropdown-item v-for="(item,index) in initData.classes" :key="index"><div @click="handleOperate(item.name,{},'add')" class="btn-add">{{item.label}}</div></el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <el-table
          v-loading="table_data.loading"
          ref="multipleTable"
          :data="table_data.list"
          stripe
          border
          size="medium"
          :height="tableHeight"
          style="width: 100%">
          <el-table-column label="序号" type="index" width="55" align="center" fixed />
          <el-table-column label="污染源名称" prop="name" width="200" fixed />
          <el-table-column label="区县" prop="county" />
          <el-table-column label="镇街" prop="town" />
          <el-table-column label="行业类型" prop="class" />
          <el-table-column prop="so2" width="120">
            <template slot="header" slot-scope="scope">
              <div class="flex-block" @click="getRange('so2')">
                <div class="title">SO₂排放量<br/>（吨/年）</div>
                <img :src="searchForm.order_by == 'so2' ? icon.blue : icon.grey" width="18px"/>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="nox" width="120">
            <template slot="header" slot-scope="scope">
              <div class="flex-block" @click="getRange('nox')">
                <div class="title">NOx排放量<br/>（吨/年）</div>
                <img :src="searchForm.order_by == 'nox' ? icon.blue : icon.grey" width="18px"/>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="pm10" width="120">
            <template slot="header" slot-scope="scope">
              <div class="flex-block" @click="getRange('pm10')">
                <div class="title">PM₁₀排放量<br/>（吨/年）</div>
                <img :src="searchForm.order_by == 'pm10' ? icon.blue : icon.grey" width="18px"/>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="pm25" width="120">
            <template slot="header" slot-scope="scope">
              <div class="flex-block" @click="getRange('pm25')">
                <div class="title">PM₂.₅排放量<br/>（吨/年）</div>
                <img :src="searchForm.order_by == 'pm25' ? icon.blue : icon.grey" width="18px"/>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="vocs" width="120">
            <template slot="header" slot-scope="scope">
              <div class="flex-block" @click="getRange('vocs')">
                <div class="title">VOCs排放量<br/>（吨/年）</div>
                <img :src="searchForm.order_by == 'vocs' ? icon.blue : icon.grey" width="18px"/>
              </div>
            </template>
          </el-table-column> 
          <el-table-column label="操作" fixed="right" width="240px">
            <template slot-scope="scope">
              <el-link :underline="false" class="m-r-10 " type="primary" icon="el-icon-view" @click="handleOperate(getComponentsName(scope.row.class), scope.row, 'view')">详情</el-link>
              <el-link :underline="false" class="m-r-10" type="primary" icon="el-icon-edit" @click="handleOperate(getComponentsName(scope.row.class),scope.row, 'edit')">编辑</el-link>
              <el-link :underline="false" class="m-r-10" type="primary" icon="el-icon-location-outline" @click="handleOperate('showMap', scope.row)">位置</el-link>
              <el-link :underline="false" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :current-page="page.current"
          :page-size="page.size"
          :page-sizes="page_sizes"
          :total="page.total"
          background
          style="padding-top: 30px; text-align: center;"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="getList"
          @size-change="pageSizeChange"
        />
    </template>
    <edit-industry ref="editIndustry" @save="getList(page.current)" />
    <edit-dust ref="editDust" @save="getList(page.current)" />
    <edit-oil ref="editOil" @save="getList(page.current)" />
    <edit-restaurant ref="editRestaurant" @save="getList(page.current)" />
    <show-map ref="showMap" />
  </page-lr>
</template>
<script>
import editIndustry from './components/editIndustry';
import editDust from './components/editDust';
import editOil from './components/editOil';
import editRestaurant from './components/editRestaurant';
import showMap from './components/showMap';
export default {
  components: {
    editIndustry,
    editDust,
    editOil,
    editRestaurant,
    showMap,
  },
  data() {
    return{
      searchForm:{
        industries:[],
        county: '全市',
        class: [],
        name: null,
        order_by: null,
        nox: null,
        pm10: null,
        pm25: null,
        so2: null,
        vocs: null,
      },
      defaultSearchForm:{},
      table_data:{
        loading: true,
        list: [],
      },
      page:{
        current: 1,
        size: 10,
        total: 0,
      },
      page_sizes:[10,20,30,60,100],
      isCheckedAll: true,
      indeterminate: false,
      checkedAllIndustries: true,
      indeterminateIndustries: false,
      initData:{
        allIndustries: [],
        industries: [],
        areas : [
          { label: '不限', value: 0 },
          { label: '1公里', value: 1 },
          { label: '3公里', value: 3 },
          { label: '5公里', value: 5 },
        ],
        stations: [],
        countys: [
          {name: '全市', value: ''},
          {name: '香洲区', value: ''},
          {name: '金湾区', value: ''},
          {name: '斗门区', value: ''},
          {name: '高新区', value: ''},
          {name: '鹤洲新区', value: ''},
          {name: '横琴粤澳深度合作区', value: ''}
        ],
        classes:[
        { label: '工业源', value: 1, name: 'editIndustry',color: '#FE5656', icon: require('@/assets/images/icons/工业源.png') },
          { label: '扬尘源', value: 2, name: 'editDust',color: '#EAEA26', icon: require('@/assets/images/icons/扬尘源.png')},
          { label: '油站油库', value: 3, name: 'editOil',color: '#01E17E', icon: require('@/assets/images/icons/油站油库.png') },
          { label: '大型餐饮', value: 4, name: 'editRestaurant',color: '#3DD1F9', icon: require('@/assets/images/icons/大型餐饮.png') },
        ],
        stationsChecked: [],
        location: [],
      },
      icon:{
        grey: require('@/assets/images/icons/icon-sort-grey.png'),
        blue: require('@/assets/images/icons/icon-sort-blue.png'),
      },
      domHeight: 0,
      tableHeight: 0,
      userInfo:{},
    }
  },
  created(){
    this.table_data.loading = false;
    this.isRegionUser();
    this.getInitData();
  },
  watch:{
    $route(to,from){
      this.$refs.multipleTable.doLayout();
    }
  },
  methods:{
    isRegionUser(){
      this.userInfo = this.$store.getters.currentUserInfo;
      if(this.userInfo.is_region_user){
        this.searchForm.county = this.userInfo.region_code;      
      }
    },
    async getInitData(){
      this.domHeight = document.body.clientHeight - 64 - 40 - 48*2 - 10;
      this.tableHeight = this.domHeight -47-60;
      this.searchForm.class = this.initData.classes.map(item => item.label);
      this.initData.stations = await this.$request('get', '/air/stations', {});    
      this.initData.stationsChecked = this.initData.stations.map(item => item.id);  
      let allIndustries = await this.$request('get', '/stations/ind_code', {});
      this.getIndustries(allIndustries);
      this.getList();

    },
    getIndustries(allIndustries){
      this.initData.allIndustries = allIndustries;    
      let newIndustries = allIndustries.map(item => {
        item.label = item.value + ' | ' + item.text;
        return item;
      });
      this.initData.industriesTree = this.$util.getTreeList(newIndustries, {
        parentId: 'parent_id'
      });
      this.initData.industriesTree = this.changeTree(this.initData.industriesTree);
      let industries = [];
      this.initData.industriesTree.forEach(item => {
        industries = industries.concat(item.children);
      });
      this.initData.industries = industries.filter(item => {
        return Number(item.value) > 4 && Number(item.value) < 47;
      });
      this.searchForm.industries = this.initData.industries.map(item => item.text);
      this.defaultSearchForm = JSON.parse(JSON.stringify(this.searchForm));
    },
    changeTree(data){
      let arr = data.map(item => {
        if(!item.hasOwnProperty('children')){
          item.label = item.value4 + ' | ' + item.text;
        }else{
          item.children = this.changeTree(item.children);
        };
        return item;
      });
      return arr;
    },
    changeClass(val){
      if(val.indexOf('工业源') == -1){
        this.searchForm.industries = this.initData.industries.map(item => item.text);
        this.indeterminateIndustries = false;
      }
    },
    changeCheckAllIndustries(val){
      let arr = [];
      if(val){
        arr = this.initData.industries.map(item => item.text);
        this.indeterminateIndustries = false;
      }
      this.searchForm.industries = arr;
    },
    changeIndustries(val){
      let len = this.initData.industries.length;
      let n = val.length;
      if(n == 0){
        this.checkedAllIndustries = false;
        this.indeterminateIndustries = false;
      }else if(n > 0 && n < len){
        this.indeterminateIndustries = true;
      }else if(n == len){
        this.indeterminateIndustries = false
      }
    },
    getSearchParams(){
      let params = {};
      for(let key in this.searchForm){
        if(this.searchForm[key] && !Array.isArray(this.searchForm[key])){
          params[key] = this.searchForm[key];
        }
      };
      if(this.searchForm.county == '全市'){
        delete params.county;
      }
      if(this.searchForm.class.length > 0){
        params.class = this.searchForm.class
      }

      if(this.searchForm.class.indexOf('工业源') != -1 && this.searchForm.industries.length > 0){
        params.indtype_level2 = this.searchForm.industries
      }      
      return params;
    },
    getList(page, size) {
      let params = {
        page_num : page || 1,
        page_count : size || this.page.size
      };
      params.page_num -= 1;

      this.table_data.loading = true;
      this.$request('post', '/stations/ind_sel'+this.$util.serialize(params), this.getSearchParams(), (data, msg) => {
        if(data.datas.length > 0){
          this.table_data.list = data.datas.map(item => {
            item.so2 = this.getNumber(item.so2);
            item.nox = this.getNumber(item.nox);
            item.pm10 = this.getNumber(item.pm10);
            item.pm25 = this.getNumber(item.pm25);
            item.vocs = this.getNumber(item.vocs);
            return item;
          });
        }else{
          this.table_data.list = [];
        }
        this.page.total = data.total;
        this.table_data.loading = false;
        this.getListCallback();
      }, (msg) => {
        this.table_data.loading = false;
      })
    },
    pageSizeChange(val){
      this.page.size=val;
      this.getList(1, val);
    },	
    resetSearch(){
      this.$util.resetForm(this.searchForm, this.defaultSearchForm);
      this.getList();
    },
    getRange(type){
      if(this.searchForm.order_by == type){
        this.searchForm.order_by = null;
      }else{
        this.searchForm.order_by = type;
      }
      this.getList(this.page.current);
    },
    getNumber(val){
      if(Number(val) == 0){
        return 0;
      }else{
        return Number(val).toFixed(2)
      }
    },
    getComponentsName(data){
      let name;
      switch(data){
        case '工业源':
          name = 'editIndustry';
          break;
        case '扬尘源':
          name = 'editDust';
          break;
        case '油站油库':
          name = 'editOil';
          break;
        case '大型餐饮':
          name = 'editRestaurant';
          break;
      }
      return name;
    },
    handleOperate(name,row,type){
      this.$refs.editIndustry.isShow = false;
      this.$refs.editDust.isShow = false;
      this.$refs.editOil.isShow = false;
      this.$refs.editRestaurant.isShow = false;
      this.$refs[name].init(row, type);
    },
    handleDelete(row){
      this.$confirm('确定要删除【'+row.name+'】这个污染源?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$request('get', '/stations/ind_del',{id: row.id}, (data,msg) => {
            this.$message.success(msg);
            this.getList(this.page.current);
          })
        }).catch(() => {
                   
        });
    }
  }

}
</script>